package com.koron.order.overhaul.filter;

import com.alibaba.fastjson.JSON;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.org.dto.OrgDto;
import com.koron.bean.system.post.query.PostUserQuery;
import com.koron.bean.system.post.vo.PostUserVo;
import com.koron.bean.workflow.SubmitterParam;
import com.koron.bean.workflow.WorkflowUser;
import com.koron.common.core.business.system.feign.SystemFeignService;
import com.koron.common.core.util.CommonUtils;
import com.koron.order.overhaul.bean.entity.OverhaulOrderBean;
import org.apache.commons.collections4.CollectionUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author twcao
 * @title: OverhaulFilter
 * @projectName GDH_EAM_V2
 * @description: TODO
 * @date 2022/1/1915:33
 */
@Component
public class OverhaulFilter {

    @Autowired
    private SystemFeignService systemFeignService;

    /**
     * 主办单位提案 配置 站室主任会审审批人
     * @param factory
     * @param submitterParam
     * @return
     */
    @TaskAnnotation("task0Submitter")
    public List<WorkflowUser> task0Submitter(SessionFactory factory, SubmitterParam submitterParam) {
        OverhaulOrderBean order = JSON.parseObject(submitterParam.getFormVariables(), OverhaulOrderBean.class);
        // 只发送到创建人所在单位的主任、站长
        List<WorkflowUser> users = filter(factory, account(submitterParam), postCode(submitterParam), Arrays.asList(order.getDeptId()));
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        return users;
    }

    /**
     * 站室主任会审 配置 站设备管理部门机电副总、维修部分管副总会审审批人
     * @param factory
     * @param submitterParam
     * @return
     */
    @TaskAnnotation("task1Submitter")
    public List<WorkflowUser> task1Submitter(SessionFactory factory, SubmitterParam submitterParam) {
        OverhaulOrderBean order = JSON.parseObject(submitterParam.getFormVariables(), OverhaulOrderBean.class);
        // 设备所属单位
        String deptManage = order.getDeptManage();
        // 设备管理单位所属部门
        List<String> deptIds = getDeptIdByOrgId(Arrays.asList(deptManage));
        // 维修部
        deptIds.addAll(orgs(submitterParam));
        // 只发送至设备管理单位所在部门的部门副总经理、和维修部的部门副总经理（安全）
        // 岗位：部门副总经理、部门副总经理（安全）
        List<String> postCodes = postCode(submitterParam);
        if(CollectionUtils.size(deptIds) != CollectionUtils.size(postCodes)) {
            return filter(factory, account(submitterParam), postCode(submitterParam), deptIds);
        }
        List<WorkflowUser> users = new ArrayList<>();
        for (int i = 0, size = postCodes.size(); i < size; i++) {
            // 1、设备管理单位所在部门的部门副总经理
            // 2、维修部的部门副总经理（安全）
            users.addAll(filter(factory, account(submitterParam), Arrays.asList(postCodes.get(i)), Arrays.asList(deptIds.get(i))));
        }
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        return users;
    }

    /**
     * 站设备管理部门机电副总、维修部分管副总会审 配置 技术部专业管理审批审批人
     * @param factory
     * @param submitterParam
     * @return
     */
    @TaskAnnotation("task2Submitter")
    public List<WorkflowUser> task2Submitter(SessionFactory factory, SubmitterParam submitterParam) {
        // 生产技术部机械管理（岗位）
        List<WorkflowUser> users = filter(factory, account(submitterParam), postCode(submitterParam), orgs(submitterParam));
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        return users;
    }

    /**
     * 获取岗位
     * @param submitterParam
     * @return
     */
    private List<String> postCode(SubmitterParam submitterParam) {
        List<WorkflowUser> users = submitterParam.getUsers();
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        // 岗位编码
        List<String> postCodes = users.stream().filter(row -> row.getType() == 2).map(WorkflowUser::getCode).collect(Collectors.toList());
        return postCodes;
    }

    /**
     * 人员
     * @param submitterParam
     * @return
     */
    private List<String> account(SubmitterParam submitterParam) {
        List<WorkflowUser> users = submitterParam.getUsers();
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        // 人员账号
        List<String> userAccounts = users.stream().filter(row -> row.getType() == 0).map(WorkflowUser::getCode).collect(Collectors.toList());
        return userAccounts;
    }

    /**
     * 组织
     * @param submitterParam
     * @return
     */
    private List<String> orgs(SubmitterParam submitterParam) {
        List<WorkflowUser> users = submitterParam.getUsers();
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        // 人员组织
        List<String> orgs = users.stream().filter(row -> row.getType() == 1).map(WorkflowUser::getCode).collect(Collectors.toList());
        return orgs;
    }

    /**
     * 根据岗位和组织查询审批人
     * 人员列表 && 组织列表 && 岗位列表
     * @param factory 会话
     * @param accounts 人员列表
     * @param orgList 组织列表
     * @param postCodes 岗位列表
     * @return
     */
    private List<WorkflowUser> filter(SessionFactory factory, List<String> accounts, List<String> postCodes, List<String> orgList) {
        if(CollectionUtils.isEmpty(postCodes) && CollectionUtils.isEmpty(orgList)) {
            return null;
        }
        PostUserQuery query = new PostUserQuery();
        query.setPostIdList(postCodes);
        query.setOrgIdList(orgList);
        List<PostUserVo> vos = CommonUtils.ok(systemFeignService.queryPostList(query));
        List<WorkflowUser> users = new ArrayList<>();
        vos.stream().forEach(vo -> {
            WorkflowUser user = new WorkflowUser();
            if(!CollectionUtils.isEmpty(accounts) && !accounts.contains(user.getCode())) {
                return;
            }
            user.setCode(vo.getUserAccount());
            user.setName(vo.getUserName());
            users.add(user);
        });
        return users;
    }

    private List<String> getDeptIdByOrgId(List<String> orgIds) {
        OrgDto orgDto = new OrgDto();
        orgDto.setOrgIds(orgIds);
        List<OrgBean> depts = CommonUtils.ok(systemFeignService.queryDeptByOrgIdList(orgDto));
        return depts.stream().map(OrgBean::getDeptId).collect(Collectors.toList());
    }
}
